package com.chushouya.manager.dao.repository;

import com.chushouya.manager.dao.entity.ArticleEntity;
import com.chushouya.manager.dao.mapper.ArticleEntityMapper;
import com.chushouya.manager.dto.admin.article.ArticleQuery;
import com.general.framework.core.lang.Numbers;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Article repository for database operations
 */
@Repository
public class ArticleRepository extends BaseRepository<ArticleEntityMapper,ArticleEntity,Long> {

    /**
     * 查询文章分页列表
     *
     * @param query 查询条件
     * @return 分页列表
     */
    public PageResult<ArticleEntity> selectPage(ArticleQuery query) {
        return selectPage(query, buildExample(query));
    }

    public List<ArticleEntity> selectList(ArticleQuery query) {
        return selectByExample(buildExample(query));
    }

    /**
     * 查询文章分页列表
     *
     * @param query 查询条件
     * @return 分页列表
     */
    public ArticleEntity selectOne(ArticleQuery query) {
        return selectFirstOneByExample(buildExample(query));
    }

    private Example buildExample(ArticleQuery query) {
        Example example = buildExample();
        Example.Criteria c = example.and();
        c.andEqualTo("delFlag", Numbers.INTEGER_ZERO);
        if (query.getCategoryId() != null) {
            c.andEqualTo("categoryId", query.getCategoryId());
        }
        if (Strings.isNotBlank(query.getTitle())) {
            c.andLike("categoryName", Strings.format("%{}%", query.getTitle()));
        }
        c.andEqualTo("delFlag", Numbers.INTEGER_ZERO);
        example.orderBy("sort").orderBy("categoryId").desc();
        return example;
    }
}
